package cms.factory;

import cms.factory.config.TableBeanConfig;
import cms.factory.create.TableBean;
import cms.utils.ModifyClass;
import cms.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 后置处理器，可以修改bean的配置信息
 */
@Slf4j
@Component
public class BeanFactoryPost implements InitializingBean {
    @Autowired
    Map<String, TableBeanConfig> tableBeanConfigMap;
    @Autowired
    TableBean tableBeanCreate;

//    /**
//     * 主要是用来自定义修改持有的bean
//     * ConfigurableListableBeanFactory 其实就是DefaultListableBeanDefinition对象
//     * @param beanFactory
//     * @throws BeansException
//     */
//    @Override
//    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
//            throws BeansException {
//
//    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //动态修改类
        ModifyClass.escapeXmlELResolverGetValue();
//        Map<String, TableBeanConfig> tableBeanConfigMap = beanFactory.getBeansOfType(TableBeanConfig.class);
        if (MapUtils.isNotEmpty(tableBeanConfigMap)) {
//            TableBean tableBeanCreate = beanFactory.getBean(TableBean.class);
            for (String key : tableBeanConfigMap.keySet()) {
                log.info("初始化{}开始", key);
                TableBeanConfig tableBeanConfig = tableBeanConfigMap.get(key);
                Integer tableQuantity = tableBeanConfig.getTableQuantity();
                if (tableQuantity != null && tableQuantity > 1) {
                    for (int i = 1; i < tableQuantity; i++) {
                        tableBeanCreate.create(tableBeanConfig.getTableClazz(), i, tableBeanConfig.getSerialVersionTag());
                    }
                }
            }
        }
    }
}
